package com.shopping.controller;

import com.alibaba.fastjson.JSONObject;
import com.shopping.constant.ResponseCode;
import com.shopping.pojo.Appraise;
import com.shopping.pojo.Order;
import com.shopping.pojo.ShoppingCart;
import com.shopping.pojo.Trade;
import com.shopping.service.order.OrderServiceImpl;
import com.shopping.service.store.StoreServiceImpl;
import com.shopping.service.trade.TradeServiceImpl;
import com.shopping.util.BeanValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class TradeController {

    @Autowired
    TradeServiceImpl tradeService;
    @Autowired
    OrderServiceImpl orderService;
    @Autowired
    StoreServiceImpl storeService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @PostMapping(value = {"/trade/putAway"})
    public Map<String, Object> putAwayTrade(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        Trade trade = new Trade();
        trade.setTradeName(jsonObject.getString("tradeName"));
        trade.setTradeIntroduce(jsonObject.getString("tradeIntroduce"));
        trade.setType1(jsonObject.getString("type1"));
        trade.setType2(jsonObject.getString("type2"));
        trade.setPrice(jsonObject.getFloat("price"));
        trade.setSpecification(jsonObject.getString("specification"));
        trade.setInventory(jsonObject.getInteger("inventory"));
        trade.setCarriage(jsonObject.getFloat("carriage"));
        trade.setStoreId(jsonObject.getInteger("storeId"));
        trade.setPic1(jsonObject.getString("pic1"));
        if(jsonObject.getString("pic2") != null){
            trade.setPic2(jsonObject.getString("pic2"));
        }
        if(jsonObject.getString("pic3") != null){
            trade.setPic3(jsonObject.getString("pic3"));
        }
        if(jsonObject.getString("pic4") != null){
            trade.setPic4(jsonObject.getString("pic4"));
        }
        if(jsonObject.getString("pic5") != null){
            trade.setPic5(jsonObject.getString("pic5"));
        }
        Map<String, Object> map = new HashMap<>();
        if(!BeanValidator.validate(trade)){
            map.put("code", ResponseCode.PARAM_ERROR.getValue());
            return map;
        }
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        Map<String, Object> result = storeService.selectStoreIdByUserId(redisUserId);
        if(result.get("code").equals(ResponseCode.REQUEST_SUCCESSED)){
            int selectStoreId = Integer.parseInt(String.valueOf(result.get("storeId")));
            if(selectStoreId == trade.getStoreId()){
                return tradeService.addTrade(trade);
            }
        }
        map.put("code", ResponseCode.SERVER_ERROR.getValue());
        return map;
    }

    @PostMapping(value = {"/trade/outOfStock"})
    public Map<String, Object> outOfStock(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        int tradeId = jsonObject.getInteger("tradeId");
        Map<String, Object> map = new HashMap<>();
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        Map<String, Object> result = storeService.selectStoreIdByUserId(redisUserId);
        if(result.get("code").equals(ResponseCode.REQUEST_SUCCESSED)){
            int selectStoreId = Integer.parseInt(String.valueOf(result.get("storeId")));
            Map<String, Object> result2 = tradeService.showTradeMessageById(tradeId);
            if(result2.get("code").equals(ResponseCode.REQUEST_SUCCESSED.getValue())){
                int storeId = Integer.parseInt(String.valueOf(result2.get("trade")));
                if(selectStoreId == storeId){
                    return tradeService.outOfStock(tradeId);
                }
            }
        }
        map.put("code", ResponseCode.SERVER_ERROR.getValue());
        return map;
    }

    @PostMapping(value = {"/trade/showTradeMessageById"})
    public Map<String, Object> showTradeMessageById(@RequestBody JSONObject jsonObject){
        System.out.println("object: " + jsonObject);
        int tradeId = Integer.parseInt(jsonObject.getString("tradeId"));
        System.out.println("tradeId: " + tradeId);
        return tradeService.showTradeMessageById(tradeId);
    }

    @PostMapping(value = {"/trade/showTradeMessageByStoreAndTradeName"})
    public Map<String, Object> showTradeMessageByStoreAndTradeName(@RequestBody JSONObject jsonObject){
        int storeId = jsonObject.getInteger("storeId");
        String tradeName = jsonObject.getString("tradeName");
        return tradeService.showTradeMessageByStoreAndTradeName(storeId, tradeName);
    }

    @PostMapping(value = {"/trade/appraiseTrade"})
    public Map<String, Object> appraiseTrade(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        Appraise appraise = new Appraise();
        appraise.setTradeId(jsonObject.getInteger("tradeId"));
        appraise.setStoreId(jsonObject.getInteger("storeId"));
        appraise.setAnonymity(jsonObject.getBoolean("isAnonyMity"));
        appraise.setAppraiseContent(jsonObject.getString("appraiseContent"));
        appraise.setTradeGrade(jsonObject.getInteger("tradeGrade"));
        appraise.setStoreGrade(jsonObject.getInteger("storeGrade"));
        appraise.setTransportGrade(jsonObject.getInteger("transportGrade"));
        if(jsonObject.getString("pic1") != null){
            appraise.setPic1(jsonObject.getString("pic1"));
        }
        if(jsonObject.getString("pic2") != null){
            appraise.setPic2(jsonObject.getString("pic2"));
        }
        if(jsonObject.getString("pic3") != null){
            appraise.setPic3(jsonObject.getString("pic3"));
        }
        Map<String, Object> map = new HashMap<>();
        if(!BeanValidator.validate(appraise)){
            map.put("code", ResponseCode.PARAM_ERROR.getValue());
            return map;
        }
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        appraise.setUserId(redisUserId);
        Map<String, Object> result = orderService.isOrderExist(appraise.getUserId(), appraise.getStoreId(), appraise.getTradeId());
        if(Integer.parseInt(String.valueOf(result.get("code"))) == ResponseCode.REQUEST_SUCCESSED.getValue()){
            return tradeService.addAppraise(appraise);
        }
        return result;
    }

    @PostMapping(value = {"/trade/purchase"})
    public Map<String, Object> purchase(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        int tradeId = jsonObject.getInteger("tradeId");
        int addNum = jsonObject.getInteger("addNum");
        Map<String, Object> map = new HashMap<>();
        if(addNum < 0){
            map.put("code", ResponseCode.PARAM_ILLEGAL.getValue());
            return map;
        }
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        Map<String, Object> result = storeService.selectStoreIdByUserId(redisUserId);
        if(result.get("code").equals(ResponseCode.REQUEST_SUCCESSED)){
            int selectStoreId = Integer.parseInt(String.valueOf(result.get("storeId")));
            Map<String, Object> result2 = tradeService.showTradeMessageById(tradeId);
            if(result2.get("code").equals(ResponseCode.REQUEST_SUCCESSED.getValue())){
                int storeId = Integer.parseInt(String.valueOf(result2.get("trade")));
                if(selectStoreId == storeId){
                    return tradeService.increaseInventory(tradeId, addNum);
                }
            }
        }
        map.put("code", ResponseCode.SERVER_ERROR.getValue());
        return map;
    }

    @PostMapping(value = {"/trade/buyTrade"})
    public Map<String, Object> buyTrade(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        Order order = new Order();
        order.setTradeId(jsonObject.getInteger("tradeId"));
        order.setNumber(jsonObject.getInteger("number"));
        order.setTime(jsonObject.getDate("time"));
        order.setReceiveId(jsonObject.getInteger("receiveId"));
        order.setTransportNum(jsonObject.getString("transportNum"));
        order.setStoreId(jsonObject.getInteger("storeId"));
        Map<String, Object> map = new HashMap<>();
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        order.setUserId(redisUserId);
        if(!BeanValidator.validate(order)){
            map.put("code", ResponseCode.PARAM_ILLEGAL.getValue());
            return map;
        }
        Map<String, Object> result = tradeService.buyTrade(order);
        if(Integer.parseInt(String.valueOf(result.get("code"))) == ResponseCode.REQUEST_SUCCESSED.getValue()){
            return orderService.addOrder(order);
        }else{
            return result;
        }
    }

    @PostMapping(value = {"/trade/collectionTrade"})
    public Map<String, Object> collectionTrade(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        int tradeId = jsonObject.getInteger("tradeId");
        int fansId = jsonObject.getInteger("fansId");
        Map<String, Object> map = new HashMap<>();
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        Map<String, Object> result = storeService.selectStoreIdByUserId(redisUserId);
        if(result.get("code").equals(ResponseCode.REQUEST_SUCCESSED)){
            int selectStoreId = Integer.parseInt(String.valueOf(result.get("storeId")));
            Map<String, Object> result2 = tradeService.showTradeMessageById(tradeId);
            if(result2.get("code").equals(ResponseCode.REQUEST_SUCCESSED.getValue())){
                int storeId = Integer.parseInt(String.valueOf(result2.get("trade")));
                if(selectStoreId == storeId){
                    return tradeService.addFans(tradeId, fansId);
                }
            }
        }
        map.put("code", ResponseCode.SERVER_ERROR.getValue());
        return map;
    }

    @PostMapping(value = {"/trade/addToShoppingCart"})
    public Map<String, Object> addToShoppingCart(@RequestBody JSONObject jsonObject){
        String uuid = jsonObject.getString("uuid");
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setTradeId(jsonObject.getInteger("tradeId"));
        shoppingCart.setStoreId(jsonObject.getInteger("storeId"));
        shoppingCart.setNumber(jsonObject.getInteger("number"));
        Map<String, Object> map = new HashMap<>();
        if(!BeanValidator.validate(shoppingCart)){
            map.put("code", ResponseCode.PARAM_ERROR.getValue());
            return map;
        }
        int redisUserId = (int) stringRedisTemplate.opsForHash().get(uuid, "userId");
        if(stringRedisTemplate.opsForHash().get(uuid, "openid") == null){
            map.put("code", ResponseCode.SERVER_ERROR.getValue());
            return map;
        }
        shoppingCart.setUserId(redisUserId);
        return tradeService.addShoppingCart(shoppingCart);
    }

    @PostMapping(value = {"/trade/showTypes"})
    public Map<String, Object> showTypes(){
        return tradeService.showTypes();
    }

}
